package com.hs.telepass.manager;

import android.content.Context;
import com.hs.telepass.MainApp;
import com.hs.telepass.controller.TaskController;
import com.hs.telepass.dao.SingouProfilesDatabase;
import com.hs.telepass.model.QrCodeModal;
import com.hs.telepass.model.SingouProfiles;
import com.hs.telepass.model.json.Requst.BaseQrIdJson;
import com.hs.telepass.model.json.Requst.SendAuthReqJson;
import com.hs.telepass.model.json.Requst.StartSingouSessionRequstJson;
import com.hs.telepass.model.RepositoryProfile;
import com.hs.telepass.utils.DeviceInfoUtil;
import com.hs.telepass.utils.JsonUtil;
import com.hs.telepass.utils.StringUtil;
import com.hs.telepass.utils.security.AESEnc;
import com.hs.telepass.utils.security.Base64Utils;
import com.hs.telepass.utils.security.Cert;
import com.hs.telepass.utils.security.RSA;

import org.apache.commons.codec.digest.DigestUtils;

import java.math.BigInteger;

/**
 * 
 * @author szw
 * 
 * @modified edvard
 * @time 2014-10-4
 */
public class SingouManager {
    private static SingouManager mInstance;
    private Context mContext;
    private String mSid;
    private String mRuntimeKey;

    public SingouManager(){
        mContext = MainApp.getInstance();
    }

    public static SingouManager getInstance(){
        if(null == mInstance)
            mInstance = new SingouManager();
        return mInstance;
    }

    public void startSingouSession(String accountid, String password, String runtime_key, boolean isFromUpdate) throws Exception {
        String uuid = DeviceInfoUtil.getDeviceId(mContext);

        int os = 2;
        int lang = 2;
        /**
         * 将返回的字节数转换为16进制的数
         */
        byte[] data = DigestUtils.sha1(password);
        String shaPassword = String.format("%0" + (data.length * 2) + "X", new BigInteger(1, data)).toLowerCase();
        
        StartSingouSessionRequstJson startSingouSessionRequstJson = new StartSingouSessionRequstJson();
        startSingouSessionRequstJson.setUuid(uuid);
        startSingouSessionRequstJson.setRuntime_key(runtime_key);
        startSingouSessionRequstJson.setAccountid(accountid);
        startSingouSessionRequstJson.setOs(os);
        startSingouSessionRequstJson.setLang(lang);
        startSingouSessionRequstJson.setPassword(shaPassword);

        String basejson = JsonUtil.toJson(startSingouSessionRequstJson);

        Cert cert = new Cert(mContext, "public.der");
        String encJson = cert.pubKeyEncrypt(basejson);

        TaskController.getInstance().startSingouSession(mContext,runtime_key, encJson, isFromUpdate);
    }

    public void initSingouAuth(String qrId, String sid, String runtime_key) throws Exception {
        BaseQrIdJson json = new BaseQrIdJson();
        json.setId(qrId);
        AESEnc enc = new AESEnc(runtime_key.getBytes());
        byte[] encByte = enc.encrypt(JsonUtil.toJson(json).getBytes());

        String req = Base64Utils.encode(encByte);

        TaskController.getInstance().initSingouAuth(mContext, sid, req);
    }

    public void sendAuth(String sid, String username, String password, String qrId, String runtime_key) throws Exception {
        SendAuthReqJson sendAuthReqJson = new SendAuthReqJson();
        sendAuthReqJson.setId(qrId);
        sendAuthReqJson.setLoginID(username);

        String reqJson = JsonUtil.toJson(sendAuthReqJson);
        AESEnc enc = new AESEnc(runtime_key.getBytes());
        String reqAes = Base64Utils.encode(enc.encrypt(reqJson.getBytes()));

        Cert cert = new Cert(mContext, "test.web.public.der");

        String encrypted_payload = cert.pubKeyEncrypt(password);

        TaskController.getInstance().sendAuth(mContext, sid, reqAes, encrypted_payload);
    }


    public void getAuthStatus(String sid, String qrId, String runtime_key) throws Exception {
        BaseQrIdJson json = new BaseQrIdJson();
        json.setId(qrId);

        String reqJson = JsonUtil.toJson(json);
        AESEnc enc = new AESEnc(runtime_key.getBytes());
        String reqAes = Base64Utils.encode(enc.encrypt(reqJson.getBytes()));

        TaskController.getInstance().getAuth(mContext, sid, reqAes);
    }

    public void insertSingouProfile(QrCodeModal qrCodeModal, String username, String password){
        SingouProfiles profile = new SingouProfiles();
        profile.setUsername(username);
        profile.setEncrytedPassword(password);
        profile.setServiceID(qrCodeModal.getS());
        profile.setServiceName(qrCodeModal.getN());

        RepositoryProfile qrProfile = qrCodeModal.getProfile();
        profile.setTile(qrProfile.getTitle());
        profile.setLogoURL(qrProfile.getLogoURL());
        if(ProfilesManager.getInstance().hasTotallySameSingouProfile(profile))
            new SingouProfilesDatabase(mContext).updateProfile(profile.getProfileID(), profile.getUsername(), profile.getEncrytedPassword());
        else
            new SingouProfilesDatabase(mContext).addRecord(profile);
    }

    /**
     * 用来判断是否有初始singou 密码
     * */
    public boolean hasSingouPassword(){
        return StringUtil.isEmpty(PreferencesManager.getInstance().getPasswordKey());
    }

    public void setSid(String sid){
        this.mSid = sid;
    }

    public String getSid(){
        return this.mSid;
    }

    public void setRuntimeKey(String runtimeKey){
        this.mRuntimeKey = runtimeKey;
    }

    public String getRuntimeKey(){
        return this.mRuntimeKey;
    }
}
